<?php
namespace addons\jieziarea\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
class Qqmap extends Command
{
    //original
    private $provinces = null;
    private $citys = null;
    private $districts = null;
    private $direct_citys = ['北京', '上海', '重庆', '天津', '香港', '澳门'];
    private $base_url = 'https://apis.map.qq.com/ws/district/v1/getchildren';

    //insert
    private $insert_tree = [];

    private $original = 0;
    private $fullname = 0;
    protected function configure()
    {
        $this->setName('qqmap')
            ->addOption('original', 'o', Option::VALUE_REQUIRED, 'is original', 0)
            ->addOption('fullname', 'f', Option::VALUE_REQUIRED, 'is full name', 0)
            ->setDescription('get area data')
            ;
    }

    protected function execute(Input $input, Output $output){
        $this->original = $input->getOption('original') ?: 0;
        $this->fullname = $input->getOption('fullname') ?: 0;

        $qqmap_service_key = get_addon_config('qqmap_service_key');
        if(empty($qqmap_service_key)){
            $qqmap_service_key = 'CVUBZ-F7SCZ-GVXXM-ZY3IJ-QBFKQ-PQFUO';
        }
        $this->base_url = $this->base_url . '?key=' . $qqmap_service_key;

        $qqmap_cache_key = 'qqmap_cache';
        $res = \think\Cache::get($qqmap_cache_key);
        $res = false;
        if(!$res){
            $res = json_decode(file_get_contents($this->base_url), true);
            \think\Cache::set($qqmap_cache_key, $res);
        }else{

        }
//        var_dump($res);

        debug('start');
        if(!$res['status']){
            //省
            $this->provinces = $res['result'][0];

            foreach($res['result'][0] as $idx => $province){
                $this->insert_tree[$province['id']] = [
                    'id' => $province['id'],
                    'pid' => 0,
                    'name' => $this->fullname ? $province['fullname'] : $province['name'],
                    'level' => 0,
                    'lng' => $province['location']['lng'],
                    'lat' => $province['location']['lat'],
                ];
//                $this->getChild($idx, 0, $this->insert_tree[$province['id']]);
//                var_dump($province['cidx']);die;
//                if(!in_array($province['name'], $this->direct_citys)){
//                    $this->getDistrict($province);
//                }else {
                    $this->getCity($province);
//                }
            }
            file_put_contents(ROOT_PATH . 'area.php', '<?php return ' . var_export($this->insert_tree, true) . ';');
            $output->writeln('over');
//            var_dump('over');die;
            //直辖区
//            $directly_districts = [];
//            try {
//                foreach ($citys as $idx => $city) {
//                    $province_id = substr($city['id'], 0, 2) . '0000';
//                    $city_id = substr($city['id'], 0, 4) . '00';
//                    if (empty($city['cidx'])) {
//                        foreach ($provinces as $province) {
//                            if ($idx >= $province['cidx'][0] && $idx <= $province['cidx'][1]) {
////                                var_dump($city, $province);die;
//                                $insert_citys[$city_id] = [
//                                    'id' => $city_id,
//                                    'pid' => $province['id'],
//                                    'name' => $province['name'],
//                                    'level' => 1,
//                                ];
//
//                                $directly_districts[$city['id']] = [
//                                    'id' => $city['id'],
//                                    'pid' => $city_id,
//                                    'name' => $fullname ? $city['fullname'] : $city['name'],
//                                    'level' => 2,
//                                ];
//                            }
//                        }
////                    var_dump($directly_districts, $city, $insert_citys);die;
//                    } else {
//                        $insert_citys[$city['id']] = [
//                            'id' => $city['id'],
//                            'pid' => $province_id,
//                            'name' => $fullname ? $city['fullname'] : $city['name'],
//                            'level' => 1,
//                        ];
//                    }
//                }
//            }catch (\Exception $e){
//                var_dump($e->getLine());die;
//            }
//
//            try{
//                foreach($districts as $district){
//                    $city_id = substr($district['id'], 0, 4) . '00';
//                    $pid = !empty($insert_citys[$city_id]) ? $city_id : (!empty($directly_districts[$city_id]) ? $city_id : 0);
//                    $insert_districts[$district['id']] = [
//                        'id' => $district['id'],
//                        'pid' => $city_id,
//                        'name' => $fullname ? $district['fullname'] : (empty($district['name']) ? $district['fullname'] : $district['name']),
//                        'level' => 2,
//                    ];
//                }
//            }catch (\Exception $e){
//                var_dump($e->getLine());die;
//            }

//            var_dump($directly_districts);die;
            $area_model = new \addons\jieziarea\model\Jieziarea();
            $area_model->where('id', '>', 0)->delete();
            $area_model->insertAll($this->insert_tree);
//            $area_model->insertAll($insert_provinces);
//            $area_model->insertAll($insert_citys);
//            $area_model->insertAll($insert_districts);
//            $directly_districts && $area_model->insertAll($directly_districts);
            $output->writeln(debug('start', 'end'));
        }else{
            $output->writeln($res['message']);
        }
    }

    //城市
    private function getCity($province){
//        if(in_array($province['name'], $this->direct_citys)) {
//            var_dump($province);
//        }
//        return 1;
        sleep(1);
        $res = json_decode(file_get_contents($this->base_url . '&id=' . $province['id']), true);
        if(!$res['status']){
            //直辖市
            if(in_array($province['name'], $this->direct_citys)){
//                var_dump($province);
                $pid = 0;
                if($province['name'] == '重庆') {
                    $pid = 501000;
                }
                if($province['name'] == '香港') {
                    $pid = 810100;
                }
                if($province['name'] == '澳门') {
                    $pid = 821000;
                }
                if($province['name'] == '台湾') {
                    $pid = 710100;
                }
                foreach($res['result'][0] as $idx => $district) {
                    if(!$pid) {
                        $pid = substr_replace($district['id'], '00', 4);
                    }
                    $this->insert_tree[$district['id']] = [
                        'id' => $district['id'],
                        'pid' => $pid,
                        'name' => $this->fullname ? $district['fullname'] : $district['name'],
                        'level' => 3,
                        'lng' => $district['location']['lng'],
                        'lat' => $district['location']['lat'],
                    ];
                }
                $this->insert_tree[$pid] = [
                    'id' => $pid,
                    'pid' => $province['id'],
                    'name' => $this->fullname ? $province['fullname'] : $province['name'],
                    'level' => 2,
                    'lng' => $province['location']['lng'],
                    'lat' => $province['location']['lat'],
                ];
//                if($province['name'] == '重庆') {
                    var_dump($pid, $res['result'][0]);
//                    die;
//                }
            }else{
                foreach($res['result'][0] as $idx => $city) {
                    $this->insert_tree[$city['id']] = [
                        'id' => $city['id'],
                        'pid' => $province['id'],
                        'name' => $this->fullname ? $city['fullname'] : $city['name'],
                        'level' => 2,
                        'lng' => $city['location']['lng'],
                        'lat' => $city['location']['lat'],
                    ];
                    $this->getDistrict($city);
                }
            }
        }else{
            var_dump($res);
        }

//        var_dump($province);die;
    }

    //区县
    private function getDistrict($city){
        sleep(1);
        $res = json_decode(file_get_contents($this->base_url . '&id=' . $city['id']), true);

        if(!$res['status']) {
            foreach ($res['result'][0] as $idx => $district) {
                $this->insert_tree[$district['id']] = [
                    'id' => $district['id'],
                    'pid' => $city['id'],
                    'name' => $district['fullname'],
                    'level' => 3,
                    'lng' => $district['location']['lng'],
                    'lat' => $district['location']['lat'],
                ];
            }
        }
    }
}